package com.example.cameraapp.fragment;

import android.os.Environment;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;

import com.example.cameraapp.util.LogUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MyAlbumFragmentAdapter extends FragmentPagerAdapter {

    private final int PAGER_COUNT = 1;

    public MyAlbumFragmentAdapter(FragmentManager fm) {
        super(fm);
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        return super.instantiateItem(container, position);
    }

    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        System.out.println("there will no fragment be destroyed");
        super.destroyItem(container, position, object);
    }

    @Override
    public Fragment getItem(int position) {
        return new MyAlbumFragment(getLatestAlbum());
    }

    @Override
    public int getCount() {
        return PAGER_COUNT;
    }

    //    获取本软件自定义目录下最新的照片
    private String getLatestAlbum() {
        String rootPath = new File(String.valueOf(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_DCIM)), "CameraTestStorage").toString() + "/";
        File albumDirectory = new File(rootPath);
        if (albumDirectory.isDirectory()) {
            List<String> fileList = new ArrayList<>();
            for (File file : Objects.requireNonNull(albumDirectory.listFiles())) {
                fileList.add(file.toString());
            }
            int maxID = 0;
            long maxLong = 0L;
            String reg = "(?<=" + rootPath + ")\\d{13}(?=\\.jpg)";
            Pattern r = Pattern.compile(reg);
            for (int i = 0; i < fileList.size(); i++) {
                Matcher matcher = r.matcher(fileList.get(i));
                while (matcher.find()) {
                    if (Long.parseLong(matcher.group()) > maxLong) {
                        maxID = i;
                        maxLong = Long.parseLong(matcher.group());
                    }
                }
            }
            LogUtil.log("最新照：" + fileList.get(maxID));
            return fileList.get(maxID);
        }
        return "";
    }
}